/**
 * Copyright 2008 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kiff.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Provider Proxy Class.
 * @author Adam
 * @version $Id: ProviderProxy.java 62 2008-10-31 04:51:50Z a.ruggles $
 * 
 * Created on Oct 8, 2008 at 7:15:26 PM 
 * @param <T> The Provider Type.
 */
public class ProviderProxy<T> implements InvocationHandler {

	/**
	 * Provider of Type T.
	 */
	protected final Provider<T> provider;

	/**
	 * Constructs a proxy with a provider of type T.
	 * @param provider
	 */
	public ProviderProxy(final Provider<T> provider) {
		this.provider = provider;
	}

	/**
	 * {@inheritDoc}
	 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
	 */
	public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
		Object result;
		try {
			result = method.invoke(provider.get(), args);
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		} catch (Exception e) {
			throw e;
		}
		return result;
	}
}
